package com.demo.config;

import com.demo.myconst.MyConst;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.io.IOException;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.demo"})
public class SpringMVCConfig implements WebMvcConfigurer {
    /**
     * 配置视图解析器
     */
    @Bean
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    /**
     * 配置静态资源 不需要DispatcherServlet 转发的请求
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    /**
     * 文件上传的配置
     */
    @Bean("multipartResolver")
    public CommonsMultipartResolver getMultipartResolver() {
        CommonsMultipartResolver cmr = new CommonsMultipartResolver();
        //设置请求的编码格式。默认为UTF-8
        cmr.setDefaultEncoding("UTF-8");
        //设置允许上传文件的最大值。单位为字节
        //100MB
        cmr.setMaxUploadSize(100 * 1024 * 1024);
        //设置上传文件的临时路径
        Resource uploadTempDir = new FileSystemResource(MyConst.UPLOAD_PATH_TEMP);
        try {
            cmr.setUploadTempDir(uploadTempDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cmr;
    }
}
